package com.zby.business.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.zby.business.util.Util;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZBY on 2015/12/14.
 */
public class DetailViewPagerAdapter extends PagerAdapter {
    private String[] urls;
    private LayoutInflater inflater;
    private Context context;
    private ImageLoader imageLoader;
    private LruCache cache;

    public DetailViewPagerAdapter(Context context, String[] urls) {
        this.urls = urls;
        inflater = LayoutInflater.from(context);
        this.context = context;
        imageLoader = ImageLoader.getInstance();
        cache = new LruCache((int) (Runtime.getRuntime().maxMemory() / 20));
    }

    @Override
    public int getCount() {
        return urls.length - 1;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return super.getPageTitle(position);
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        ImageView imageView = new ImageView(context);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        imageView.setLayoutParams(params);
        Bitmap bitmap = (Bitmap) cache.get(urls[position + 1]);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        } else {
            imageLoader.displayImage(Util.BASE_URL + urls[position + 1], imageView);
            imageLoader.loadImage(Util.BASE_URL + urls[position + 1], new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {

                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {

                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    cache.put(urls[position + 1], bitmap);
                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });
        }
        container.addView(imageView);
        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }
}
